package com.sea.onlinejudge.common.interceptor;

import com.sea.onlinejudge.common.annotation.Login;
import com.sea.onlinejudge.common.exception.MException;
import com.sea.onlinejudge.common.utils.JwtTokenUtil;
import com.sea.onlinejudge.common.utils.StringUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限登录拦截
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            if (((HandlerMethod)handler).getMethod().getAnnotation(Login.class) == null) {
                return true;
            }
        } else {
            return true;
        }
//        System.out.println("header: -----------------------> :" + jwtTokenUtil.getHeader());
        String token = request.getHeader(jwtTokenUtil.getHeader());
        if (StringUtil.isBlank(token)) {
            token = request.getParameter(jwtTokenUtil.getHeader());
        }

        //凭证为空
        if (StringUtil.isBlank(token)) {
            throw new MException("凭证为空", HttpStatus.UNAUTHORIZED.value());
        }
        Claims claims = jwtTokenUtil.getClaims(token);
        if (jwtTokenUtil.isTokenExpired(claims.getExpiration())) {
            throw new MException("登录凭证失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
//        Integer userId = Integer.valueOf(claims.getAudience());

        return true;
    }
}
